// pages/my-processing-edit/my-processing-edit.ts
// 加工编辑页，结构基于 publish-processing
import { getPublishDetail, editPublish } from '../../../api/publish.js'
import { getCategoryNames, getProductsByCategory } from '../../../config/product-categories.js'
import { goBack } from '../../../config/pages.js'

interface SpecItem {
  mm: string;
  m: string;
}

interface FormData {
  product_category: string;
  product_name: string;
  product_model: string;
  processing_accuracy: string;
  processing_width: string;
  processing_equipment: string;
  specs: SpecItem[];
  total_amount: string;
  remark: string;
  contact_name: string;
  contact_phone: string;
  contact_email: string;
  province: string;
  city: string;
  district: string;
  province_id: number;
  city_id: number;
  district_id: number;
  detail_address: string;
}

Page({
  data: {
    id: '',
    loading: true,
    publishType: 'processing', // 单据类型：加工
    formData: {
      product_category: '',
      product_name: '',
      product_model: '',
      processing_accuracy: '',
      processing_width: '',
      processing_equipment: '',
      specs: [
        { mm: '', m: '' }
      ],
      total_amount: '',
      remark: '',
      contact_name: '',
      contact_phone: '',
      contact_email: '',
      province: '',
      city: '',
      district: '',
      province_id: 0,
      city_id: 0,
      district_id: 0,
      detail_address: ''
    } as FormData,
    
    categoryList: getCategoryNames(),
    productList: [] as string[],
    showCategoryPicker: false,
    showProductPicker: false,
    categoryIndex: 0,
    productIndex: 0,
    
    uploadedImages: [] as string[],
    uploadedImageUrls: [] as string[],
    uploadingImages: false,
    
    submitting: false
  },

  onLoad(options: any) {
    const { id } = options;
    if (id) {
      this.setData({ id });
      this.loadDetail();
    } else {
      wx.showToast({
        title: '参数错误',
        icon: 'none',
      });
      setTimeout(() => {
        goBack();
      }, 1500);
    }
  },

  async loadDetail() {
    this.setData({ loading: true });

    try {
      const res = await getPublishDetail(this.data.id);

      if ((res.status === 200 || res.code === 200) && res.data) {
        const detail = res.data;
        
        // 保存单据类型
        if (detail.type) {
          this.setData({ publishType: detail.type });
        }
        
        let specs = [{ mm: '', m: '' }];
        if (detail.spec) {
          try {
            const parsedSpecs = typeof detail.spec === 'string' 
              ? JSON.parse(detail.spec) 
              : detail.spec;
            if (Array.isArray(parsedSpecs) && parsedSpecs.length > 0) {
              specs = parsedSpecs;
            }
          } catch (e) {
            console.error('解析规格数据失败:', e);
          }
        }
        
        const categoryIndex = this.data.categoryList.indexOf(detail.product_category || '');
        const productList = detail.product_category 
          ? getProductsByCategory(detail.product_category) 
          : [];
        const productIndex = productList.indexOf(detail.product_name || '');
        
        let uploadedImages = [];
        let uploadedImageUrls = [];
        if (detail.product_image_atts && Array.isArray(detail.product_image_atts)) {
          uploadedImages = detail.product_image_atts;
          uploadedImageUrls = detail.product_image_atts.map((img: any) => img.url);
        } else if (detail.product_images && Array.isArray(detail.product_images)) {
          uploadedImageUrls = detail.product_images;
          uploadedImages = detail.product_images.map((url: string) => ({ url }));
        }
        
        this.setData({
          formData: {
            product_category: detail.product_category || '',
            product_name: detail.product_name || '',
            product_model: detail.product_model || '',
            processing_accuracy: detail.processing_accuracy || '',
            processing_width: detail.processing_width || '',
            processing_equipment: detail.processing_equipment || '',
            specs: specs,
            total_amount: detail.total_amount || '',
            remark: detail.remark || '',
            contact_name: detail.contact_name || '',
            contact_phone: detail.contact_phone || '',
            contact_email: detail.contact_email || '',
            province: detail.province || '',
            city: detail.city || '',
            district: detail.district || '',
            province_id: detail.province_id || 0,
            city_id: detail.city_id || 0,
            district_id: detail.district_id || 0,
            detail_address: detail.detail_address || ''
          },
          productList: productList,
          categoryIndex: categoryIndex >= 0 ? categoryIndex : 0,
          productIndex: productIndex >= 0 ? productIndex : 0,
          uploadedImages: uploadedImages,
          uploadedImageUrls: uploadedImageUrls,
          loading: false,
        });
      } else {
        wx.showToast({
          title: res.msg || '加载失败',
          icon: 'none',
        });
        this.setData({ loading: false });
      }
    } catch (error: any) {
      console.error('加载详情失败:', error);
      wx.showToast({
        title: typeof(error) === 'string' ? error : (error?.message || '加载失败'),
        icon: 'none',
      });
      this.setData({ loading: false });
    }
  },

  onModelInput(e: any) {
    this.setData({
      'formData.product_model': e.detail.value
    });
  },

  onProcessingAccuracyInput(e: any) {
    this.setData({
      'formData.processing_accuracy': e.detail.value
    });
  },

  onProcessingWidthInput(e: any) {
    this.setData({
      'formData.processing_width': e.detail.value
    });
  },

  onProcessingEquipmentInput(e: any) {
    this.setData({
      'formData.processing_equipment': e.detail.value
    });
  },

  onRemarkInput(e: any) {
    this.setData({
      'formData.remark': e.detail.value
    });
  },

  onContactNameInput(e: any) {
    this.setData({
      'formData.contact_name': e.detail.value
    });
  },

  onContactPhoneInput(e: any) {
    this.setData({
      'formData.contact_phone': e.detail.value
    });
  },

  onEmailInput(e: any) {
    this.setData({
      'formData.contact_email': e.detail.value
    });
  },

  onTotalAmountInput(e: any) {
    this.setData({
      'formData.total_amount': e.detail.value
    });
  },

  onDetailAddressInput(e: any) {
    this.setData({
      'formData.detail_address': e.detail.value
    });
  },

  showCategoryPicker() {
    this.setData({
      showCategoryPicker: true
    });
  },

  showProductPicker() {
    this.setData({
      showProductPicker: true
    });
  },

  onCategoryPickerChange(e: any) {
    const index = e.detail.value[0];
    this.setData({
      categoryIndex: index
    });
  },

  onProductPickerChange(e: any) {
    const index = e.detail.value[0];
    this.setData({
      productIndex: index
    });
  },

  hideCategoryPicker() {
    this.setData({
      showCategoryPicker: false
    });
  },

  confirmCategoryPicker() {
    const index = this.data.categoryIndex || 0;
    const category = this.data.categoryList[index];
    const products = getProductsByCategory(category);
    this.setData({
      'formData.product_category': category,
      'formData.product_name': '',
      productList: products,
      productIndex: 0,
      showCategoryPicker: false
    });
  },

  hideProductPicker() {
    this.setData({
      showProductPicker: false
    });
  },

  confirmProductPicker() {
    const index = this.data.productIndex || 0;
    const product = this.data.productList[index];
    this.setData({
      'formData.product_name': product,
      showProductPicker: false
    });
  },

  onSpecInput(e: any) {
    const { index, type } = e.currentTarget.dataset;
    const value = e.detail.value;
    const specs = [...this.data.formData.specs];
    (specs[index] as any)[type] = value;
    this.setData({
      'formData.specs': specs
    });
  },

  addSpecItem() {
    const specs = [...this.data.formData.specs];
    specs.push({ mm: '', m: '' } as SpecItem);
    this.setData({
      'formData.specs': specs
    });
  },

  removeSpecItem(e: any) {
    const index = e.currentTarget.dataset.index;
    const specs = [...this.data.formData.specs];
    specs.splice(index, 1);
    this.setData({
      'formData.specs': specs
    });
  },

  onImageUploadSuccess(e: any) {
    const { allImages, allImageUrls } = e.detail;
    this.setData({
      uploadedImages: allImages,
      uploadedImageUrls: allImageUrls
    });
  },

  onImageRemove(e: any) {
    const { remainingImages, remainingImageUrls } = e.detail;
    this.setData({
      uploadedImages: remainingImages,
      uploadedImageUrls: remainingImageUrls
    });
  },

  onAddressChange(e: any) {
    const { address } = e.detail;
    if (address) {
      this.setData({
        'formData.province': address.province,
        'formData.city': address.city,
        'formData.district': address.district,
        'formData.province_id': address.province_id,
        'formData.city_id': address.city_id,
        'formData.district_id': address.district_id
      });
    }
  },

  async saveEdit() {
    if (!this.validateForm()) {
      return;
    }

    this.setData({ submitting: true });

    wx.showLoading({
      title: '保存中...'
    });
    
    try {
      const submitData: any = {
        ...this.data.formData,
        type: this.data.publishType, // 添加单据类型
        spec: JSON.stringify(this.data.formData.specs || [])
      };
      
      if (this.data.uploadedImages.length > 0) {
        submitData.product_image_atts = JSON.stringify(
          this.data.uploadedImages.map((img: any) => ({
            url: img.url,
            name: img.name || '产品图片',
            size: img.size,
            path: img.path
          }))
        );
      }

      const result = await editPublish(this.data.id, submitData);
      
      if (result.status === 200 || result.code === 200) {
        wx.hideLoading();
        wx.showToast({
          title: '保存成功',
          icon: 'success'
        });
        setTimeout(() => {
          goBack();
        }, 1500);
      } else {
        wx.hideLoading();
        wx.showToast({
          title: result.msg || '保存失败',
          icon: 'none'
        });
        this.setData({ submitting: false });
      }
    } catch (error: any) {
      console.error('保存失败:', error);
      wx.hideLoading();
      wx.showToast({
        title: typeof(error) === 'string' ? error : (error?.msg || '保存失败，请重试'),
        icon: 'none'
      });
      this.setData({ submitting: false });
    }
  },

  validateForm(): boolean {
    const { formData } = this.data;
    
    if (!formData.product_category) {
      wx.showToast({
        title: '请选择产品类别',
        icon: 'none'
      });
      return false;
    }
    
    if (!formData.product_name) {
      wx.showToast({
        title: '请选择产品名称',
        icon: 'none'
      });
      return false;
    }
    
    if (!formData.product_model.trim()) {
      wx.showToast({
        title: '请输入产品型号',
        icon: 'none'
      });
      return false;
    }
    
    if (!formData.contact_name.trim()) {
      wx.showToast({
        title: '请输入联系人姓名',
        icon: 'none'
      });
      return false;
    }
    
    if (!formData.contact_phone.trim()) {
      wx.showToast({
        title: '请输入联系电话',
        icon: 'none'
      });
      return false;
    }
    
    if (!formData.province) {
      wx.showToast({
        title: '请选择联系地址',
        icon: 'none'
      });
      return false;
    }
    
    if (!formData.detail_address.trim()) {
      wx.showToast({
        title: '请输入详细地址',
        icon: 'none'
      });
      return false;
    }
    
    return true;
  }
});

